<?php
class MySqlAdminController extends Controller {
	public function init() {
		
	}
	
	/**
	 * 
	 * 
	 */
	public function actionProcessList() {
		$sql = 'SHOW PROCESSLIST';
		// `Id`,`User`,`Host`,`db`,`Command`,`Time`,`State`,`Info`,`Rows_sent`,`Rows_examined`,`Rows_read`
		$data = Yii::app ()->db->createCommand ( $sql )->queryAll ();
		
		$this->render ( 'processlist', array (
				'processListData' => $data 
		) );
	}
	
	/**
	 */
	public function actionIndex() {
		echo 'index';
	}
	
	// SHOW TABLE STATUS FROM teamtop_ework;
	public function actionShowTableStatus() {
		// print_r(Yii::app()->db->connectionString);
		$match = preg_match ( '/[a-z]+[a-z]$/i', Yii::app ()->db->connectionString, $matches );
		// print_r($matches[0]);
		$dbName = $matches [0];
		$sql = "SHOW TABLE STATUS FROM " . $dbName;
		// echo $sql;
		$data = Yii::app ()->db->createCommand ( $sql )->queryAll ();
		
		$this->render ( 'showtablestatus', array (
				'showTableStatusData' => $data 
		) );
	}
	public function actionShowColumns() {
		// SHOW COLUMNS from users from webapp like 'username'
	}
	public function actionShowCreateDatabse() {
		// SHOW CREATE DATABASE webapp
	}
	public function actionColumns() {
		
		
		$match = preg_match ( '/[a-z]+[a-z]$/i', Yii::app ()->db->connectionString, $matches );
		$dbName = $matches [0];
		
		$sql = "SHOW TABLE STATUS FROM " . $dbName;

		$data = Yii::app ()->db->createCommand ( $sql )->queryAll ();
		
		$comments = array();
		foreach ($data as $t=>$table){
			$comments[$table['Name']] = $table['Comment'];
		}
		
		$sql = "SHOW TABLES FROM " . $dbName;
		$tb = $dbTable = Yii::app ()->db->createCommand ( $sql )->queryColumn ();
		$column = array ();		
		foreach ( $tb as $table ) {
			$sql = "SHOW FULL COLUMNS FROM " . $dbName . '.' . $table;
			// echo '<br>' . $sql; // die();
			$column [$table] = Yii::app ()->db->createCommand ( $sql )->queryAll ();
			
			// if (++$i>3) break;
			// print_r($column);
			// echo '<br>' . "SHOW CREATE TABLE table " . $dbName . '.' .
			// $table;
		}
		// print_r($comments);
		$this->render ( 'column', array (
				'column' => $column , 'Provider'=>$comments
		) );
		// echo $sql;
	}
	
	/**
	 *
	 * @param string $search        	
	 * @param bool $prefix        	
	 * @return $databases
	 */
	private function showDbOrTable($dbTable, $search = '', $prefix = true) {
		if (! empty ( $search ))
			$conditon = ($prefix) ? "like " . $search . "%" : "like %" . $search . "%";
		$name = ($dbTable == 'tables') ? $dbTable : "databases";
		$sql = "show $name " . $conditon; // like '" . $search . "'";
		$databases = Yii::app ()->db->createCommand ( $sql )->queryAll ();
		return $databases;
	}
	
	// show tables like 'wdb_%';
	
	public function actionSetting(){
		$this->render('setting');
	}
}

?>